// pages/house/RentalHouseDetail/com/development/development.js
import api from '../../../../../common/api'
import utils from '../../../../../utils/util'
import * as user from '../../../../../models/user'
import {
  dialog
} from './../../../../../component/userStatusDialog/control'

const app = getApp();

Component({
  /**
   * 组件的配置
   */
  options: {
    styleIsolation: 'isolated',
    pureDataPattern: /^_/
  },

  /**
   * 组件的属性列表
   */
  properties: {
    houseInfo: {
      type: Object,
      value: {}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    _isRefreshVipStatus: false,
    _isRefreshFollow: false,
    vipStatus: '',
    officialAccountStatus: '',
    isShowDue: false,
    history: [],
    estate: {},
    isSubscribe: false,
    isHidePage: true,
  },

  /**
   * 组件的数据监听
   */
  observers: {
    houseInfo(val) {
      app.globalData.loginPromise.then(() => {
        if (!val) return;
        this.loadLatestDevelopment()
        this.loadDevelopmentOverview()
          .then(() => {
            this.checkSubmitOpenCity()
            this.setData({
              isHidePage: false
            })
          })
          .catch(() => {
            this.setData({
              isHidePage: false
            })
          })
      })
    }
  },

  /**
   * 组件的生命周期
   */
  lifetimes: {
    attached: function () {
      app.globalData.loginPromise.then(() => {
        this.checkVip()
        this.checkOfficialAccount()
      })
    },
    detached: function () {},
  },

  /**
   * 页面的生命周期
   */
  pageLifetimes: {
    show: function () {
      this.refreshOfficialAccount()
      this.refreshVip()
    },
    hide: function () {
      // 页面被隐藏
    },
    resize: function (size) {
      // 页面尺寸变化
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 开通vip
    onOpenVip() {
      this.data._isRefreshVipStatus = true
      wx.navigateTo({
        url: '/pages/mine/memberCentre/memberCentre?orderEntr=新上房源列表',
      })
    },

    // 关注公众号
    onFollow() {
      this.data._isRefreshFollow = true
      let url = 'https://mp.weixin.qq.com/s/I8sdEESdeHIoKLyYVnDcYQ'
      wx.navigateTo({
        url: `/pages/webView/webView?webViewUrl=${url}`
      })
    },

    // 用户vip状态校验
    checkVip() {
      user.updateVip()
        .then(res => {
          this.setData({
            vipStatus: res,
          })
          if (res !== '0') {
            this.setData({
              isShowDue: true
            })
          }
        })
    },

    // 用户vip状态更新
    refreshVip() {
      if (this.data._isRefreshVipStatus) {
        this.data._isRefreshVipStatus = false
        user.getVip()
          .then(res => {
            this.setData({
              vipStatus: res,
            })
            if (res === '0') {
              this.setData({
                isShowDue: false
              })
            }
          })
      }
    },

    // 用户公众号状态校验
    checkOfficialAccount() {
      return new Promise((resolve, reject) => {
        user.getOfficialAccount()
          .then(res => {
            if (res === '1') {
              this.setData({
                officialAccountStatus: res,
              })
              resolve()
            } else {
              reject()
            }
          })
          .catch(() => {
            wx.showToast({
              icon: 'none',
              title: '网络错误，请稍后再试~',
            })
          })
      })
    },

    // 用户公众号状态更新
    refreshOfficialAccount() {
      if (this.data._isRefreshFollow) {
        this.data._isRefreshFollow = false
        user.updateOfficialAccount()
          .then(res => {
            this.setData({
              officialAccountStatus: res,
            })
          })
      }
    },

    // 加载小区情报概览
    async loadDevelopmentOverview() {
      return new Promise(async (resolve, reject) => {
        try {
          const {
            id
          } = this.data.houseInfo.houDelVO || {}
          const res = await api.getExternalCountByDelId({
            delId: id
          })
          if (res && res.data && res.data.content) {
            const {
              hdResblockId,
              isSoldOutNum,
              monthLookNum,
              newPushNum,
              priceNum,
              hdResblockName,
              city,
              cityCode,
              area,
              bizcircleName
            } = res.data.content
            this.setData({
              estate: {
                hdResblockId,
                cityCode,
                houseCommunityName: hdResblockName || '',
                houseCityName: city || '',
                houseDistrict: area || '',
                houseBizcircleName: bizcircleName || '',
                isSoldOutNum: isSoldOutNum || 0,
                monthLookNum: monthLookNum || 0,
                newPushNum: newPushNum || 0,
                priceNum: priceNum || 0,
              }
            })
            resolve()
          } else {
            reject()
          }
        } catch (error) {
          reject()
          console.log('###err###', error);
        }
      })
    },

    // 加载最近情报
    async loadLatestDevelopment() {
      try {
        const {
          id
        } = this.data.houseInfo.houDelVO || {}
        const typeOptions = {
          MONTH_LOOK: '带看',
          PRICE: '调价',
          IS_SOLD_OUT: '下架'
        }
        const contentOptions = {
          MONTH_LOOK: '该房源在真房源网有新增带看情报',
          PRICE: '调价',
          IS_SOLD_OUT: '该房源疑似下架（在真房源网未搜索该房源）'
        }
        const res = await api.getExternalLogByHouseId({
          delId: id,
          pageNum: 1,
          pageSize: 3
        })
        if (res && res.data && res.data.content && res.data.content.list && res.data.content.list.length) {
          let history = res.data.content.list.map(item => {
            let content = '';
            if (item.externalHouseInfoType === 'PRICE') {
              item.oldPrice = item.oldPrice || 0
              item.nowPrice = item.nowPrice || 0
              let priceDifference = item.oldPrice - item.nowPrice || 0;
              let priceUpDown = priceDifference === 0 ? '调价' : priceDifference > 0 ? '下降了' : '上升了'
              content = `该房源在真房源网由${item.oldPrice / 10000}万调价${item.nowPrice / 10000}万，${priceUpDown}${Math.abs(priceDifference / 10000)}万`
            } else {
              content = contentOptions[item.externalHouseInfoType]
            }
            return {
              title: typeOptions[item.externalHouseInfoType] || '',
              time: item.createTime ? utils.dateFormat(new Date(item.createTime), "yyyy-MM-dd") : '',
              content,
            }
          })
          this.setData({
            history,
          })
        }
      } catch (error) {
        console.log('###err###', error);
      }
    },

    // 跳转情报详情
    onJumpSubscribeDetail(e) {
      const {
        vipStatus
      } = this.data
      if (vipStatus !== '0') {
        dialog({
          dialog: 'vip',
          confirm: () => {
            this.data._isRefreshVipStatus = true
            wx.navigateTo({
              url: '/pages/mine/memberCentre/memberCentre?orderEntr=新上房源详情',
            })
          }
        })
        return
      }
      const {
        hdResblockId,
        cityCode,
        houseCommunityName
      } = this.data.estate || {}
      const {
        delegationType
      } = this.data.houseInfo.houDelVO || {}
      const options = {
        newPushNum: '0',
        monthLookNum: '1',
        priceNum: '2',
        isSoldOutNum: '3'
      }
      let type = options[e.detail];
      let tab = delegationType ? delegationType.toLowerCase() : ''
      wx.navigateTo({
        url: `/pages/home/subscribe/myList/myList?id=${hdResblockId}&name=${houseCommunityName}&citycode=${cityCode}&tab=${tab}&type=${type}`,
      })
    },

    onSubscribe() {
      return new Promise((resolve, reject) => {
        const {
          isSubscribe
        } = this.data
        if (isSubscribe) return
        const {
          id
        } = this.data.houseInfo.houDelVO || {}
        api.doRequestOpenCity({
          activityCode: 'HOUSE_DETAIL_SUBSCRIBE',
          activityCode2: id
        }, (res) => {
          if (res && res.data && res.data.isSuccess) {
            this.setData({
              isSubscribe: true,
            })
            resolve()
          } else {
            reject()
          }
        })
      })
    },

    checkSubmitOpenCity() {
      return new Promise((resolve, reject) => {
        const {
          id
        } = this.data.houseInfo.houDelVO || {}
        api.checkSubmitOpenCity({
          activityCode: 'HOUSE_DETAIL_SUBSCRIBE',
          activityCode2: id
        }, (res) => {
          if (res && res.data && res.data.content) {
            this.setData({
              isSubscribe: true
            })
            resolve()
          } else {
            reject()
          }
        })
      })
    }



  }
})